<template>
  <el-card class="performance-container">
    <h3>部门绩效统计</h3>

    <!-- 🔹 月份选择器 -->
    <div class="controls">
      <el-date-picker
        v-model="selectedMonth"
        type="month"
        placeholder="选择月份"
        format="YYYY-MM"
        value-format="YYYY-MM"
        @change="handleMonthChange"
      />
    </div>

    <!-- 🔹 图表切换按钮 -->
    <el-radio-group v-model="selectedChart" class="chart-selector">
      <el-radio-button label="workload">工作量统计</el-radio-button>
      <el-radio-button label="approvalRate">审批通过率</el-radio-button>
    </el-radio-group>

    <!-- 🔹 加载中显示 -->
    <div v-if="loading" class="loading">
      <el-icon class="loading-icon"><i class="el-icon-loading" /></el-icon>
      数据加载中...
    </div>

    <!-- 🔹 图表显示 -->
    <div v-else class="chart-wrapper">
      <VChart v-if="selectedChart === 'workload'" :option="workChartOption" class="chart" />
      <VChart v-if="selectedChart === 'approvalRate'" :option="approvalChartOption" class="chart" />
    </div>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getPerformance } from '@/api/workcontent.js'
import { ElMessage } from 'element-plus'
import VChart from 'vue-echarts'
import { use } from 'echarts/core'
import { BarChart, LineChart } from 'echarts/charts'
import { CanvasRenderer } from 'echarts/renderers'
import { TooltipComponent, LegendComponent, GridComponent } from 'echarts/components'

use([TooltipComponent, LegendComponent, GridComponent, BarChart, LineChart, CanvasRenderer])

const selectedChart = ref('workload')
const loading = ref(true)
const workChartOption = ref({})
const approvalChartOption = ref({})

const userMap = ref(new Map())
const workloads = ref([])
const approvalRates = ref([])
const userIds = ref([])
const usernames = ref([])

const departmentId = ref(localStorage.getItem('departmentId'))
if (!departmentId.value) {
  ElMessage.error('无法获取部门信息，请重新登录')
}

// 🔹 新增：月份选择（默认为当前月份）
const selectedMonth = ref(new Date().toISOString().slice(0, 7)) // 格式：'2025-04'

import { getEmployeeInfo } from '@/api/user'

// 🔹 获取用户列表
const fetchUserList = async () => {
  try {
    const response = await getEmployeeInfo()
    console.log(response);
    
    if (response?.data?.code === 200) {
      userMap.value.clear()
      response.data.data.forEach((user) => {
        if (user.id !== 0 && !userMap.value.has(user.id)) {
          userMap.value.set(user.id, user.username || `用户${user.id}`)
        }
      })
      userIds.value = Array.from(userMap.value.keys())
    } else {
      ElMessage.error('获取用户信息失败！')
    }
  } catch (error) {
    console.error('error:', error)
    ElMessage.error('无法获取用户列表！')
  }
}

// 🔹 获取绩效数据（根据当前选择的月份）
const fetchAllPerformanceData = async () => {
  loading.value = true
  workloads.value = []
  approvalRates.value = []
  usernames.value = []

  try {
    for (const userId of userIds.value) {
      const response = await getPerformance(userId, selectedMonth.value)
      

      if (response?.data?.code === 200) {
        const { workload, approvalrate } = response.data.data
        if ((workload > 0 || approvalrate > 0) && userMap.value.has(userId)) {
          usernames.value.push(userMap.value.get(userId))
          workloads.value.push(typeof workload === 'number' ? workload : 0)
          approvalRates.value.push(
            typeof approvalrate === 'number' ? Math.min(approvalrate, 100) : 0,
          )
        }
      } else {
        ElMessage.error('绩效数据获取失败！')
      }
    }

    updateCharts()
  } catch (error) {
    console.error('error:', error)
    ElMessage.error('请求绩效数据时出错！')
  } finally {
    loading.value = false
  }
}

// 🔹 更新图表数据
const updateCharts = () => {
  const commonOptions = {
    tooltip: { trigger: 'axis' },
    legend: { top: '5%' },
    grid: { left: '3%', right: '4%', bottom: '8%', containLabel: true },
    xAxis: {
      type: 'category',
      data: usernames.value,
      axisTick: { alignWithLabel: true },
    },
  }

  workChartOption.value = {
    ...commonOptions,
    yAxis: { type: 'value', name: '工作量', min: 0, max: 10, interval: 2 },
    series: [
      { name: '工作量', type: 'bar', data: workloads.value, itemStyle: { color: '#409EFF' } },
    ],
  }

  approvalChartOption.value = {
    ...commonOptions,
    yAxis: { type: 'value', name: '通过率 (%)', min: 0, max: 100 },
    series: [
      {
        name: '通过率',
        type: 'line',
        data: approvalRates.value,
        itemStyle: { color: '#F56C6C' },
        lineStyle: { width: 2 },
        symbol: 'circle',
        symbolSize: 8,
      },
    ],
  }
}

// 🔹 监听月份变化
const handleMonthChange = async () => {
  if (departmentId.value) {
    await fetchAllPerformanceData()
  }
}

// 🔹 组件挂载时执行
onMounted(async () => {
  if (departmentId.value) {
    await fetchUserList()
    await fetchAllPerformanceData()
  }
})
</script>

<style scoped>
.performance-container {
  width: 100%;
  padding: 20px;
  overflow: hidden;
}

.controls {
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
}

.chart-selector {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.chart-wrapper {
  width: 100%;
  height: 400px;
  display: flex;
  justify-content: center;
}

.chart {
  width: 100%;
  height: 100%;
}

.loading {
  text-align: center;
  padding: 50px 0;
  font-size: 16px;
  color: #888;
}

.loading-icon {
  font-size: 24px;
  margin-right: 8px;
}

::-webkit-scrollbar {
  display: none;
}
</style>
